package edu.lingnan.blog.blog.service.impl;

import edu.lingnan.blog.common.core.domain.pojo.Blog;
import edu.lingnan.blog.blog.mapper.BlogMapper;
import edu.lingnan.blog.blog.service.BlogService;
import edu.lingnan.blog.common.core.constant.BlogConstants;
import edu.lingnan.blog.common.core.exception.blog.BlogStatusException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author cql
 */
@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void saveOrUpdate(Blog blog) {
        // 只有两种状态可以选择，保存为草稿和审核中
        if (!(blog.getStatus().equals(BlogConstants.DRAFT) || blog.getStatus().equals(BlogConstants.VERIFYING))) {
            throw new BlogStatusException("博客状态异常");
        }
        // 如果id为null说明是新增记录,id不为null说明是修改
        if (blog.getBlogId() != null) {
            // 如果文章正在审核中则不允许修改
            Blog temp = blogMapper.selectBlog(blog.getUserId(), blog.getBlogId());
            if (temp == null) {
                throw new BlogStatusException("博客不存在!");
            }
            if (temp.getStatus().equals(BlogConstants.VERIFYING)) {
                throw new BlogStatusException("文章正在审核中,请勿修改!");
            }
            // 修改文章
            blogMapper.updateBlog(blog);
        } else {
            // 新增文章
            blogMapper.insertBlog(blog);
        }
        // 还需要发送消息到MQ中,自动审核


    }
}
